package cn.lj.utils;
import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
/**
 * @file: JwtUtils
 * @version: 1.0
 * @Description: Jwt工具类
 * 代码目的，作用，如何工作
 * @author: 李津
 * @date: 2021-05-21 16:03
 * 本代码要注意的事项、备注事项等
 */

@Data
@Component
@ConfigurationProperties(prefix = "lj.jwt")
public class JwtUtils {

    //自定义时间
    private long expire;
    //密钥
    private String secret;
    //jwt的获取名称
    private String header;

    /**
     * 生成jwt
     * @param username
     * @return
     */
    public String generateToken(String username) {

        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * expire);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(username)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)// 7天過期
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 解析jwt
     * @param jwt
     * @return
     */
    public Claims getClaimByToken(String jwt) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * jwt是否过期
     * @param claims
     * @return
     */
    public boolean isTokenExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }


}
